import JsonP from 'jsonp'
import axio from 'axios'
import {Modal} from "antd";
import Utils from "../utils/utils";

export default class Axios {
    static requestList(_this, url, options, isMock = true) {
        this.ajax({
            url,
            isMock,
            data: options,
            method: options.method || 'get'
        }).then((res) => {
            if (res && res.result) {
                let itemList = res.result.itemList.map((item, index) => {
                    item.key = index
                    return item
                })
                _this.setState({
                    itemList,
                    pagination: Utils.pagination(res, (current) => {
                        _this.params.page = current
                        _this.requestList()
                    })
                })
            }
        })
    }

    static jsonp(options) {
        return new Promise((resolve, reject) => {
            JsonP(options.url, {
                param: 'callback'
            }, function (err, response) {
                if (response.status == 1) {
                    resolve(response)
                } else {
                    reject(response.msg)
                }
            })
        })
    }

    static ajax(options) {
        let baseApi = ''
        options.isMock = true;//TODO 上线删除
        if (options.isMock) {
            baseApi = 'https://easy-mock.com/mock/5cb7e5cac9d7e64fb56011dd/mockapi'
        } else {
            baseApi = 'https://xxx.com/mock/5cb7e5cac9d7e64fb56011dd/mockapi'
        }
        let requestMethod = options.method || 'get'
        return new Promise((resolve, reject) => {
            let requestParams = options.data || '';
            let requestObj = {
                url: options.url,
                method: requestMethod,
                baseURL: baseApi,
                timeout: 5000,
            }
            if (requestMethod == 'get') {
                requestObj.params = requestParams
            } else if (requestMethod == 'post') {
                requestObj.data = requestParams
            }
            axio(requestObj).then((response) => {
                if (response.status == 200) {
                    let res = response.data
                    if (res.code == 0) {
                        resolve(res)
                    } else {
                        Modal.error({
                            title: '提示',
                            content: res.msg
                        })
                    }
                } else {
                    reject(response.data)
                }
            })
        });
    }
}
